package cn.com.taiji.oospub.wechat.controller.register;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.HisAddressUtil;
import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.HttpClientUtil;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.*;
import cn.com.taiji.pub.BeanTools;
import cn.com.taiji.pub.StringTools;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Calendar;

import static cn.com.taiji.oospub.wechat.common.util.MessageUtil.sendMsgCode;

/**
 * 微信注册
 *
 * @author fancw
 */
@Controller
@RequestMapping("/common/wx")
public class RegisterController extends BaseLogController {
    @Autowired
    private ISchoolBaseInfoService schoolManager;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoManager;
    @Autowired
    private IDiancanSchoolurlService dianCanSchoolUrlManager;
    @Autowired
    private IMemberBmiService memberBmiService;
    @Autowired
    private IRestaurantService restaurantService;
    @Autowired
    private IReceiveAddressService receiveAddressService;
    @Autowired
    private ICustomerMinMumService customerMinMumService;
    @Autowired
    private HisAddressUtil hisAddressUtil;

    @Value("${kongxc_pos_http_server_url}")
    private String kongxc_pos_http_server_url;
    @Value("${his_address_url}")
    private String his_address_url;
    @Value("${PROPASS}")
    private String PROPASS;
    @Value("${PROJECT_CODE}")
    private String PROJECT_CODE;
    @Value("${CUS_NAME}")
    private String CUS_NAME;
    @Value("${POS_URL}")
    private String POS_URL;

    @SuppressWarnings("static-access")
    @RequestMapping(value = "/register/getCode", method = RequestMethod.POST)
    public void managePost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String mobile = request.getParameter("mobile");
        int msgcode = (int) ((Math.random() * 9 + 1) * 100000);
        String result = sendMsgCode(mobile, msgcode);
        if ("OK".equals(result)) {
            writeSuccessToBrowers(msgcode + "", response);
        } else {
            writeFailToBrowers("短息发送失败，请从新发送", response);
        }
    }


    /**
     * 就是说，我这边使用扫码方式注册的，用户注册的时候是根据用户所扫的码进行绑定项目的。
     * 员工的话应该没问题，社会人员的话，当在你那先注册了然后又来我这边注册的话，那就会有问题了。
     * 情形一：
     * 当用户在zh先注册过，后去tj这扫码
     * 问题（1）：你们把用户绑定到哪个项目了？
     * 问题（2）：重复注册？解决方案：zh开一个接口给我。参数phone，只能注册一次
     * 当用户先在tj这扫码过，后去zh注册
     * 问题（1）：不存在问题
     * 问题（2）：不存在问题
     */
    @RequestMapping(value = "/register/manage", method = RequestMethod.POST)
    @ResponseBody
    public String managePost(@RequestBody MemberBaseInfo entity, Model model, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("utf-8");
            SchoolBaseInfo schoolValidate;
//		   entity.setSchoolCode("70B2020");
            if (StringTools.hasText(entity.getSchoolCode())) {
                schoolValidate = schoolManager.findByProperty("code", entity.getSchoolCode());
                if (schoolValidate == null) {
                    model.addAttribute("result", "false");
                    model.addAttribute("message", "不存在此餐厅，请扫正确的码");
                    return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
                }
                entity.setSchoolId(schoolValidate.getId());
            } else {
                schoolValidate = schoolManager.findByProperty("code", PROJECT_CODE);
                entity.setSchoolCode(PROJECT_CODE);
                logger.info("参数项目编号projectCode丢失,使用项目默认code:{}", PROJECT_CODE);
            }
            if (entity.getMobile() != null) {
                MemberBaseInfo memberBaseInfoPhoneValidate = memberBaseInfoManager.findByPhone(entity.getMobile());
                if (memberBaseInfoPhoneValidate != null) {
                    logger.info("手机号:{}已被使用", memberBaseInfoPhoneValidate.getMobile());
                    model.addAttribute("result", "false");
                    model.addAttribute("message", "手机[" + memberBaseInfoPhoneValidate.getMobile() + "]已被使用,请检查");
                    return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
                }
            }
            String receiveAddress = entity.getReceiveAddress();
            String architecture = entity.getArchitecture();
            String hisSpaceID = entity.getHisSpaceID();
            if (StringTools.hasText(schoolValidate.getHasPos()) && "1".equals(schoolValidate.getHasPos())) {//项目有POS系统
                /*-----------------根据手机号码到pos取个人信息-----------*/
                DiancanSchoolurl dianCanSchoolUrl = dianCanSchoolUrlManager.queryByCodeAndStatus(schoolValidate.getCode(), DiancanSchoolurl.IsEffect.YX);
                HttpUtil send = new HttpUtil(dianCanSchoolUrl.getPosUrl());
                ObjectToXML toXml = new ObjectToXML();
                String resultXml = toXml.requestGetMemInfo(dianCanSchoolUrl.getPosPropass(), dianCanSchoolUrl.getPosCusName(), schoolValidate.getCode(), entity);
                System.out.println("resultXml----------------" + resultXml);
                String responseRegistXml = null;
                logger.info("oos request to pos start.registe the user.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + entity.getLoginName());
                try {
                    responseRegistXml = send.sendToBoss(resultXml);
                } catch (Exception e) {
                    logger.debug(e.getMessage());
                }
                System.err.println("responseRegistXml>>>" + responseRegistXml);
                logger.info("oos request to pos start.registe end.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + entity.getLoginName());
                MemberBaseInfo memberBaseInfo = toXml.resolveGetMemInfo(responseRegistXml);
                if ("0000".equals(memberBaseInfo.getResponseCode())) {
                    if ("1".equals(memberBaseInfo.getStatus())) {
                        String json = "{\"result\":\"false\",\"message\":\"该用户已被停用\"}";
                        return json;
                    }
                    //存在已关联的餐卡
                    CustomerMinMum customerMinMum = customerMinMumService.query().eq("customer_type_id", memberBaseInfo.getCustomerType()).one();
                    if (customerMinMum == null) {
                        customerMinMum = new CustomerMinMum();
                        customerMinMum.setCustomerTypeId(memberBaseInfo.getCustomerType());
                    }
                    customerMinMum.setMorningMinMum(memberBaseInfo.getMorningMinMum());
                    customerMinMum.setAfternoonMinMum(memberBaseInfo.getAfternoonMinMum());
                    customerMinMum.setEvenningMinMum(memberBaseInfo.getEvenningMinMum());
                    customerMinMum.setMorningAllowance(memberBaseInfo.getMorningAllowance());
                    customerMinMum.setAfternoonAllowance(memberBaseInfo.getAfternoonAllowance());
                    customerMinMum.setEveningAllowance(memberBaseInfo.getEvenningAllowance());
                    customerMinMumService.saveOrUpdate(customerMinMum);
                    memberBaseInfo.setOpenid(entity.getOpenid());
                    memberBaseInfo.setSchoolId(schoolValidate.getId());
                    BeanTools.copyProperties(memberBaseInfo, entity, "id", "openid", "schoolId", "schoolCode", "isStaff");
                } else {
                    String json = "{\"result\":\"false\",\"message\":\"未查询到员工信息\"}";
                    return json;
                }
            }
            entity.setStatusStr("0");
            if (entity.getPasswd() == null) {
                entity.setPasswd(PROPASS);
            }
            entity.setZfPasswd(entity.getPasswd());
            entity.setReceiveAddress(receiveAddress);
            entity.setArchitecture(architecture);
            entity.setHisSpaceID(hisSpaceID);
            return JSONObject.toJSONString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            String json = "{\"result\":\"false\",\"message\":\"网络异常\"}";
            return json;
        }
    }


    @RequestMapping(value = "/register/manage2", method = RequestMethod.POST)
    public void managePost2(@RequestBody MemberBaseInfo entity, HttpServletRequest request, HttpServletResponse response) throws IOException {
        SchoolBaseInfo school = schoolManager.findByProperty("Code", entity.getSchoolCode());
        entity.setSchool(school);
        entity.setSchoolId(school.getId());
        entity.setRegisterTime(LocalDateTime.now());
        entity.setLoginName(entity.getMobile());
        entity.setStatus(MemberBaseInfo.MemberStatus.NORMAL);
        //活动强度
        if (entity.getActiveStr() != null) {
            entity.setActive(MemberBaseInfo.Active.valueOf(entity.getActiveStr()));
        }
        MemberBaseInfo memberBaseInfo = memberBaseInfoManager.findByProperty("openid", entity.getOpenid());
        if (memberBaseInfo == null) {
            this.memberBaseInfoManager.save(entity);
        } else {
            BeanTools.copyProperties(entity, memberBaseInfo, "id", "weight", "height", "active", "zhOrEn", "zfPasswd", "passwd");
            this.memberBaseInfoManager.updateById(memberBaseInfo);
            //推送注册结果到POS
            String params = "?customerNo=" + entity.getIdNumber() + "&openId=" + entity.getOpenid();
            HttpClientUtil.sendPost(POS_URL + "/app/card/customer/registerWeChat" + params, null);
        }

        //保存bmi记录
        if (entity.getBmi() != null && entity.getBmi() != 0) {
            MemberBmi memberBmi = new MemberBmi();
            memberBmi.setMemberId(entity.getId());
            memberBmi.setBmi(entity.getBmi());
            memberBmi.setCreatTime(LocalDateTime.now());
            memberBmiService.save(memberBmi);
        }
        //保存送餐地址
        if (StringUtils.hasText(entity.getReceiveAddress())) {
            ReceiveAddress receiveAddress = new ReceiveAddress();
            receiveAddress.setAddress(entity.getReceiveAddress());
            receiveAddress.setArchitecture(entity.getArchitecture());
            receiveAddress.setMemberId(entity.getId());
            receiveAddress.setIsFirst("1");
            receiveAddress.setCreateTime(LocalDateTime.now());
            receiveAddress.setName(entity.getName());
            receiveAddress.setTel(entity.getMobile());
            receiveAddress.setHisSpaceID(entity.getHisSpaceID());
            receiveAddressService.save(receiveAddress);
            if (StringUtils.hasText(his_address_url) && StringUtils.hasText(entity.getHisSpaceID()) && !StringUtils.hasText(entity.getPatientNumber())) {
                entity.setPatientNumber(hisAddressUtil.getHospitalNumberByHisSpaceId(entity.getHisSpaceID()));
                memberBaseInfoManager.updateById(entity);
            }
        }
        memberBaseInfo = memberBaseInfoManager.findByProperty("openid", entity.getOpenid());

        QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_stop", false);
        queryWrapper.eq("school_id", entity.getSchoolId());

        if (restaurantService.list(queryWrapper) != null && restaurantService.list(queryWrapper).size() > 0) {
            memberBaseInfo.setRestaurant(restaurantService.list(queryWrapper).get(0));
        }
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, memberBaseInfo);
        String json = "{\"sucOrFai\":\"success\",\"message\":\"" + entity.getOpenid() + "\"}";
        writeToJson(response, json);
    }

    /**
     * 向请求方发送json字符串
     *
     * @param response
     * @throws IOException
     */
    @SuppressWarnings("unused")
    private void writeToJson(HttpServletResponse response, String json) throws IOException {
        response.setHeader("Content-Type", "text/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(json);
        writer.close();
    }


}
